package com.qfedu.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.iotserver.mapper.TenantMapper;
import com.qfedu.edu.iotserver.service.TenantService;
import com.qfedu.edu.pojo.Tenant;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.utils.SnowflakeIdGenerator;
import com.qfedu.edu.vo.TenantAuditVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
    @Autowired
    private TenantMapper tenantMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(Tenant tenant) {
        //首先校验参数的合法性
        if(null==tenant|| StringUtils.isEmpty(tenant.getName())|| StringUtils.isEmpty(tenant.getPwd())||StringUtils.isEmpty(tenant.getCompanyName())||StringUtils.isEmpty(tenant.getCompanyCode())||StringUtils.isEmpty(tenant.getDescription())||StringUtils.isEmpty(tenant.getPhone())){
           throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(),
                   ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到这里参数无误
        //那么就可以添加这个租户的信息了
        //这里还需要设置一些信息
        tenant.setEnable(1);
        //生成租户的key
        //使用UUID来生成吧
        synchronized (this){
            long key = new SnowflakeIdGenerator(1, 1).nextId();
            tenant.setAccessKey(String.valueOf(key));
            tenant.setAccessSecurit(UUID.randomUUID().toString().replace("-","").trim());
        }
        tenantMapper.insert(tenant);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void audit(TenantAuditVo tenantAuditVo) {
        if(null==tenantAuditVo||StringUtils.isEmpty(tenantAuditVo.getTenantId())||null==tenantAuditVo.getAuditStatus()){
           throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(), ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到这里 说明有数据
        //首先在这里进行查询
        Tenant tenant = tenantMapper.selectById(tenantAuditVo.getTenantId());
        if(null==tenant){
           throw new BusinessException(ResponseCode.TENANT_ID_EXCEPTION.getCode(),ResponseCode.TENANT_ID_EXCEPTION.getMsg());
        }
        tenant.setAuditStatus(tenantAuditVo.getAuditStatus());
        //执行到这里 说明参数无误 那么直接更新
        tenantMapper.updateById(tenant);
    }
}
